import socket
import json
import threading
import sys
from utils import *


class ChatClient:
    BUFFER_SIZE = 2048

    def __init__(self, nick_name):
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        # self.client_socket.bind(("", 8002))
        self.nick_name = nick_name

        self.msg_list = []
        self.chat_room = None
        self.running = False

    def recv_msg(self):
        self.running = True
        # 首先先把昵称发送给服务器
        self.client_socket.send(f"{self.nick_name}".encode())

        # 首次先接收服务器发送的消息记录
        recv_data = self.client_socket.recv(self.BUFFER_SIZE)
        recv_msgs = decode_data(recv_data)
        self.msg_list = json.loads(recv_msgs)
        print(self.msg_list)
        """
        接收消息
        :return:
        """
        while self.running:
            recv_data = self.client_socket.recv(self.BUFFER_SIZE)
            recv_msg = decode_data(recv_data)
            self.msg_list.append(json.loads(recv_msg))

    def enter(self, chat_room):
        self.chat_room = chat_room
        server = (chat_room["ip"], chat_room["port"])
        self.client_socket.connect(server)
        # 开启子线程，用来接收服务器发送的消息
        t = threading.Thread(target=self.recv_msg)
        t.daemon = True
        t.start()

        time.sleep(0.5)
        try:
            while True:
                clear_console()
                print(f"聊天室：【{self.chat_room['name']}】 共有消息：{len(self.msg_list)}条")
                print("---------------------------------------------")
                for msg in self.msg_list:
                    # {
                    #     "nickname": from_client.client_nickname,
                    #     "from": from_client.ip_port,
                    #     "message": message,
                    #     "time": current_time_str(),
                    # }
                    ip_port = msg['from']
                    nickname = msg['nickname']
                    print(f"{wrap_color(msg['time'], Color.YELLOW)} {nickname} {ip_port}：\r\n"
                          f"{msg['message']}\r\n")
                print("---------------------------------------------")
                print("【 q\t-> 退出聊天室】")
                print("【 回车\t-> 刷新聊天室】")
                print("---------------------------------------------")

                user_input = input("->")
                if user_input == 'q':
                    break
                elif user_input is None or user_input == '':
                    continue
                else:
                    self.client_socket.send(user_input.encode())
                    time.sleep(0.4)
                # 消息发之后等个接收一次消息的时间，确保消息能够及时显示
                time.sleep(0.1)
        finally:
            self.running = False
            self.client_socket.close()


if __name__ == '__main__':
    try:
        client = ChatClient("刘看山")
        client.enter(
            chat_room={
                "name": "00后聊天室",
                # "ip": "192.168.31.222",
                # "ip": "192.168.23.123",
                "ip": "192.168.23.88",
                "port": 8001,
            }
        )
    except KeyboardInterrupt as e:
        print("用户Ctrl + C退出")
        sys.exit(0)
